import React from 'react';
// import React, { Fragment } from 'react';
import { Tabs, Dropdown, Menu, Icon, Tooltip, Button } from 'antd';
// import tabPage from 'antd/lib/tabs';
// import { MenuProps } from 'antd/lib/menu';
import { FormattedMessage } from 'umi';
import _findIndex from 'lodash/findIndex';
import cn from 'classnames';
// import { connect } from 'umi';
import { callFunctionIfFunction } from '@/utils/decorators/callFunctionOrNot';
import pageTabUtil from '@/utils/pageTabUtil';
import { SubMenuWrapper } from '@/components/SubMenu';
import Footer from '@/layouts/Footer';
// import { withGlobalLoadingHook } from '@/hooks/useGlobalLoading';
import styles from './index.less';

const { TabPane } = Tabs;

const refreshCurrentTabMenuKey = 'refreshCurrent';
const closeCurrentTabMenuKey = 'closeCurrent';
const closeOthersTabMenuKey = 'closeOthers';
const closeToRightTabMenuKey = 'closeToRight';

// 用于固定第一个页签
const defaultFirstKey = '/personal/portal';
function addTab(newTab, activedTabs) {
    /**
     * filter 过滤路由 为 '/' 的 children
     * map 添加第一个 tab 不可删除
     */
    console.info('Tab新增:', newTab);
    pageTabUtil.pub(pageTabUtil.eventMap.ADD_TAB, newTab);

    let resultTabs = [...activedTabs, newTab].filter(item => item.path !== '/');

    // 固定个人主页在第一个页签
    if (!resultTabs.find(item => item.key === defaultFirstKey)) {
        const defaultFirstTab = {
            tab: '个人主页',
            key: defaultFirstKey,
            content: <></>,
            location: {
                pathname: defaultFirstKey
            }
        };
        resultTabs = [defaultFirstTab, ...resultTabs];
        pageTabUtil.needRenderFirstTab = true;
    }
    return resultTabs;
}

function updateTab({ activedTabs, activedTabIndex, updater }) {
    return activedTabs.map((tab, index) => {
        if (activedTabIndex === index) {
            const mixin = updater ? updater(tab) : {};
            return {
                ...tab,
                ...mixin
            };
        }
        return tab;
    });
}

function replaceTab({ activedTabs, currentKey, children, extraTabProperties = {}, title }) {
    const existTabIndex = _findIndex(activedTabs, { key: currentKey });
    const updater = () => ({
        tab: title,
        key: currentKey,
        content: children,
        ...extraTabProperties
    });
    return updateTab({ activedTabs, activedTabIndex: existTabIndex, updater });
}

function refreshTab({ activedTabs, activedTabIndex }) {
    const updater = tab => ({ count: (tab.count || 0) + 1 });
    return updateTab({ activedTabs, activedTabIndex, updater });
}

class ChildrenTabs extends React.PureComponent {
    static getDerivedStateFromProps(props, state) {
        const { children, activeKey: originActiveKey, activeTitle, extraTabProperties } = props;
        const { location } = extraTabProperties;
        const { pathname, query = {} } = location;
        const { activedTabs, nextTabKey, activeKey: currentKey } = state;

        const activeKey = pageTabUtil.getCurrentKey() || originActiveKey;

        /** return state and set nextTabKey to `null` after delete tab */
        if (nextTabKey) {
            return {
                activedTabs,
                activeKey: nextTabKey,
                nextTabKey: null
            };
        }

        // tab操作栏的刷新操作,左侧菜单栏的点击刷新
        if (activedTabs.length > 0 && pageTabUtil.isRefresh()) {
            const activedTabIndex = _findIndex(activedTabs, { key: currentKey });
            return {
                activedTabs: refreshTab({
                    activedTabs,
                    activedTabIndex
                })
            };
        }

        // tab内的路由跳转
        if (activedTabs.length > 0 && !pageTabUtil.isOpenSwitch()) {
            pageTabUtil.setTabHistory({
                tabKey: currentKey,
                route: {
                    pathname: originActiveKey,
                    query
                }
            });

            return {
                activedTabs: replaceTab({
                    activedTabs,
                    currentKey,
                    children,
                    extraTabProperties,
                    title: activeTitle
                })
            };
        }

        const activedTabIndex = _findIndex(activedTabs, { key: activeKey });

        /** return state after switch or update tab */
        if (activedTabIndex > -1) {
            if (pageTabUtil.isInitHistory(activeKey)) {
                console.log('init route history', extraTabProperties);
                pageTabUtil.resetHistory(activeKey, location);
                const updater = tabItem => ({
                    content: children,
                    count: (tabItem.count || 0) + 1, // 需要强制刷新
                    tab: activeTitle,
                    ...extraTabProperties
                });
                return {
                    activedTabs: updateTab({
                        activedTabs,
                        activedTabIndex,
                        updater
                    }),
                    activeKey
                };
            }

            if (pageTabUtil.needRenderFirstTab && activeKey === defaultFirstKey) {
                // 固定第一个tabKey为个人主页
                // 初始化history，并且替换content
                pageTabUtil.needRenderFirstTab = false;
                pageTabUtil.setTabHistory({
                    tabKey: defaultFirstKey,
                    route: {
                        pathname: originActiveKey,
                        query
                    }
                });
                return {
                    activeKey: defaultFirstKey,
                    activedTabs: replaceTab({
                        activedTabs,
                        currentKey: defaultFirstKey,
                        children,
                        extraTabProperties,
                        title: activeTitle
                    })
                };
            }

            // 不刷新
            return {
                activeKey
            };
        }

        /** return state to add tab */
        const newTab = {
            tab: activeTitle,
            key: activeKey,
            content: children,
            ...extraTabProperties
        };

        // init history
        pageTabUtil.setTabHistory({
            tabKey: activeKey,
            route: {
                pathname,
                query
            }
        });

        return {
            activedTabs: addTab(newTab, activedTabs),
            activeKey
        };
    }

    state = {
        activedTabs: [],
        activeKey: null,
        nextTabKey: null
    };

    handleRemoveTab = ({ key, autoRedirect }) => {
        this.remove(key, autoRedirect);
    };

    handleRefreshTab = tabKey => {
        this.handleTabRefresh(tabKey);
    };

    componentDidMount = () => {
        pageTabUtil.sub(pageTabUtil.eventMap.REMOVE_TAB, this.handleRemoveTab);
        pageTabUtil.sub(pageTabUtil.eventMap.REFRESH_TAB, this.handleRefreshTab);
    };

    componentDidUpdate = () => {
        const { activedTabs } = this.state;
        pageTabUtil.setTabsState(activedTabs);
    };

    componentWillUnmount = () => {
        pageTabUtil.unSub(pageTabUtil.eventMap.REMOVE_TAB, this.handleRemoveTab);
        pageTabUtil.unSub(pageTabUtil.eventMap.REFRESH_TAB, this.handleRefreshTab);
    };

    handleSwitch = keyToSwitch => {
        const { handleTabChange } = this.props;
        const { activedTabs } = this.state;

        callFunctionIfFunction(handleTabChange)(keyToSwitch, activedTabs);
        // 触发tab变更的事件，可以在业务页面中去订阅
        pageTabUtil.pub(pageTabUtil.eventMap.CHANGE_TAB, keyToSwitch);
    };

    handleTabEdit = async (targetKey, action) => {
        await this[action](targetKey);
        // 根据王总需求，关闭的是机构管理的列表视图，清除当前列表展开的状态
        if (targetKey === '/office/personnelManagement/organization/orgflow' && action === 'remove') {
            sessionStorage.removeItem('orgListTableExpandedRowKeys');
        }
    };

    remove = (key, autoRedirect = true) => {
        const { afterRemoveTab } = this.props;
        const { activedTabs, activeKey } = this.state;

        pageTabUtil.getTabHistory(key);
        // 删除tab history
        pageTabUtil.clearTabHistory(key);
        const targetIndex = _findIndex(activedTabs, { key });
        const removeTabItem = activedTabs[targetIndex];
        const defaultTabKey = activedTabs[targetIndex - 1]?.key ?? 0;
        const nextTabKey = key !== activeKey ? activeKey : defaultTabKey;

        const autoRedirectProps = autoRedirect ? { nextTabKey } : {};
        this.setState(
            {
                activedTabs: activedTabs.filter(item => item.key !== key),
                ...autoRedirectProps
            },
            () => {
                if (!autoRedirect) return;
                callFunctionIfFunction(afterRemoveTab)(key, nextTabKey, activedTabs);
            }
        );
        pageTabUtil.pub(pageTabUtil.eventMap.AFTER_MOVE_TAB, { key, tabItem: removeTabItem });
    };

    handleTabRefresh = tabKey => {
        // 将刷新统一处理
        pageTabUtil.setRefresh();
        this.setState({
            activeKey: tabKey
        });
    };

    handleTabsMenuClick = tabKey => event => {
        const { key } = event;
        const { activedTabs } = this.state;

        if (key === closeCurrentTabMenuKey) {
            this.remove(tabKey);
        } else if (key === closeOthersTabMenuKey) {
            const firstKey = activedTabs[0].key;
            const currentTab = activedTabs.filter(item => item.key === tabKey || item.key === firstKey);

            // 删除tab history
            activedTabs.forEach(item => {
                if (item.key !== tabKey || item.key !== firstKey) pageTabUtil.clearTabHistory(item.key);
            });

            this.setState({
                activedTabs: currentTab
            });
        } else if (key === closeToRightTabMenuKey) {
            const currentIndex = _findIndex(activedTabs, { key: tabKey });

            // 删除tab history
            activedTabs.slice(currentIndex + 1).forEach(item => pageTabUtil.clearTabHistory(item.key));

            this.setState({
                activedTabs: activedTabs.slice(0, currentIndex + 1)
            });
        } else if (key === refreshCurrentTabMenuKey) {
            this.handleTabRefresh(tabKey);
        }
    };

    render() {
        const { tabsConfig } = this.props;
        const { activedTabs, activeKey } = this.state;

        const setMenu = (key, index) => (
            <Menu onClick={this.handleTabsMenuClick(key)}>
                <Menu.Item key={refreshCurrentTabMenuKey}>
                    <FormattedMessage id="component.childrenTabs.refreshCurrent" />
                </Menu.Item>
                <Menu.Item disabled={index === 0} key={closeCurrentTabMenuKey}>
                    <FormattedMessage id="component.childrenTabs.closeCurrent" />
                </Menu.Item>
                <Menu.Item disabled={activedTabs.length === 1} key={closeOthersTabMenuKey}>
                    <FormattedMessage id="component.childrenTabs.closeOthers" />
                </Menu.Item>
                <Menu.Item disabled={activedTabs.length === index + 1} key={closeToRightTabMenuKey}>
                    <FormattedMessage id="component.childrenTabs.closeToRight" />
                </Menu.Item>
            </Menu>
        );

        const setTab = (item, key, index) => (
            <span onContextMenu={event => event.preventDefault()}>
                <Dropdown overlay={setMenu(item.key, index)} trigger={['contextMenu']}>
                    <span className={styles.tabTitle}>
                        {item.key === key && <Icon type="tag" />}
                        {item.tab}
                    </span>
                </Dropdown>
            </span>
        );

        // eslint-disable-next-line no-confusing-arrow
        const getTabToolStatus = forward => pageTabUtil.getTabHistoryStatus(activeKey, forward);
        const renderTabs = () => {
            if (activedTabs && activedTabs.length) {
                return activedTabs.map((item, index) => (
                    <TabPane
                        tab={setTab(item, activeKey, index)}
                        key={item.key}
                        closable={activedTabs.length > 1 && index !== 0}
                    >
                        <div className={cn(styles.tabHeight, 'tab-scroll-context')}>
                            <SubMenuWrapper location={item.location}>
                                {React.cloneElement(item.content, {
                                    key: item.count
                                })}
                                <Footer />
                            </SubMenuWrapper>
                        </div>
                    </TabPane>
                ));
            }
            return null;
        };

        const renderBackButton = () => {
            if (getTabToolStatus(-1)) {
                return (
                    <Tooltip placement="bottom" title="返回">
                        <div>
                            <Button icon="left" onClick={() => pageTabUtil.goTabHistory(activeKey, -1)} />
                        </div>
                    </Tooltip>
                );
            }
            return (
                <div>
                    <Button icon="left" disabled />
                </div>
            );
        };

        return (
            <div id="menuTabs" className={styles.menuTabsWrapper}>
                <div className={styles.menuTabsToolWrapper}>
                    <ul className={styles.menuTabsTool}>
                        <li>{renderBackButton()}</li>
                        <li>
                            <Tooltip placement="bottom" title="刷新">
                                <div>
                                    <Button icon="reload" onClick={() => this.handleTabRefresh(activeKey)} />
                                </div>
                            </Tooltip>
                        </li>
                    </ul>
                </div>
                {/* <Spin spinning={workFlowLoading}> */}
                <Tabs
                    className="menu-tabs"
                    tabPosition="top"
                    type="editable-card"
                    tabBarStyle={{ margin: 0 }}
                    tabBarGutter={0}
                    hideAdd
                    {...tabsConfig}
                    activeKey={activeKey}
                    onEdit={this.handleTabEdit}
                    onChange={this.handleSwitch}
                >
                    {renderTabs()}
                </Tabs>
                {/* </Spin> */}
            </div>
        );
    }
}

// export default withGlobalLoadingHook(ChildrenTabs);
export default ChildrenTabs;
